{{template "admin/header.html"}}
<style>
	.layui-form-label {
	  width: 110px;
	  padding: 9px 10px;
	}
	.layui-input-block {
	  margin-left: 130px;
	}
</style>
<title>{{T "Edit Content"}} - GPRESS</title>
<link rel="stylesheet" type="text/css" href="{{basePath}}admin/js/cherry-markdown/cherry-markdown.min.css" />
<link href="{{basePath}}admin/js/wangeditor/wangeditor5.min.css" rel="stylesheet" />
<script src="{{basePath}}admin/js/wangeditor/wangeditor5.min.js"></script>
<script type="text/javascript" src="{{basePath}}admin/js/cherry-markdown/cherry-markdown.min.js"></script>
{{template "admin/bodystart.html"}} 

{{ $categories := selectList "category" "" 1 1000 "* FROM category order by sortNo desc" }} 
{{ $themeTemplate := themeTemplate "content" }} 

<div class="layui-panel" style="padding: 5px;height: 100%;">
	<form class="layui-form" id="gpress-form" action="{{basePath}}admin/{{.UrlPathParam}}/update" method="POST" onsubmit="return false;" style="height:100%;display: flex;flex-direction: column;">
		<div class="layui-form-item">
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Path Identifier"}}</label>
				<div class="layui-input-block">
					<input type="hidden" name="id" id="id" value="{{.Data.Id}}" />
					<input type="text" class="layui-input" disabled value="{{lastURI .Data.Id}}" />
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Title"}}</label>
				<div class="layui-input-block">
					<input type="text" name="title" lay-verify="required" lay-reqtext='{{T "Please fill in the content title"}}' autocomplete="off"
						class="layui-input" value="{{.Data.Title}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Summary"}}</label>
				<div class="layui-input-block">
					<input type="text" name="summary" autocomplete="off" class="layui-input" value="{{.Data.Summary}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">Keyword</label>
				<div class="layui-input-block">
					<input type="text" name="keyword" autocomplete="off" class="layui-input" value="{{.Data.Keyword}}">
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Navigation Menu"}}</label>
				<div class="layui-input-block">
					<select name="categoryID" id="categoryID" lay-verify="required" lay-reqtext='{{T "Please select a navigation menu"}}'>
						<option value="">{{T "Please select"}}</option>
						{{ range $index,$obj := $categories.Data }}
						<option value="{{$obj.Id}}">{{$obj.Name}}</option>
						{{end}}
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Page Template"}}</label>
				<div class="layui-input-block">
					<select name="templateFile" id="templateFile">
						<option value="">{{T "Default"}}(content.html)</option>
						{{ range $index,$obj := $themeTemplate }}
						<option value="{{$obj.Name}}">{{$obj.Name}}</option>
						{{end}}
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Status"}}</label>
				<div class="layui-input-block">
					<select name="status" id="status">
						<option value="1">{{T "Public"}}</option>
						<option value="0">{{T "Link Access"}}</option>
						<option value="2">{{T "Top"}}</option>
						<option value="3">{{T "Private"}}</option>
					</select>
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">Description</label>
				<div class="layui-input-block">
					<input type="text" name="description" autocomplete="off" class="layui-input" value="{{.Data.Description}}">
				</div>
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Cover Image"}}</label>
				<div class="layui-input-block">
					<button type="button" class="layui-btn" id="button-upload-thumbnail">
						<i class="layui-icon layui-icon-upload"></i> {{T "Upload Cover"}}
					</button>
					<img height="38px" id="img_thumbnail" style="padding-left: 10px;" />
					<i id="i_delete_thumbnail" class="layui-icon layui-icon-delete" style="font-size: 20px;display: none;"></i> 
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Sort"}}</label>
				<div class="layui-input-block">
					<input type="number" name="sortNo" lay-verify="required" lay-reqtext='{{T "Please fill in the sort number"}}' autocomplete="off"
						class="layui-input" value="{{.Data.SortNo}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Author"}}</label>
				<div class="layui-input-block">
					<input type="text" name="author" autocomplete="off" class="layui-input" value="{{.Data.Author}}">
				</div>
			</div>
			<div class="layui-col-md3">
				<label class="layui-form-label">{{T "Tag"}}</label>
				<div class="layui-input-block">
					<input type="text" name="tag" autocomplete="off" class="layui-input" value="{{.Data.Tag}}">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">{{T "Content format"}}</label>
			<div class="layui-input-block">
				<input type="radio" name="contentType" value="0" title="Markdown" checked lay-filter="contentType" />
				<input type="radio" name="contentType" value="1" title='{{T "Rich Text"}}' lay-filter="contentType" />
				<button type="submit" class="layui-btn layui-bg-blue" lay-submit
					lay-filter="gpress-form-ajax-update">{{T "Submit Changes"}}</button>
			</div>
		</div>
		<div id="markdown-container" style="height: 100%;"></div>
        <div id="editor-wrapper" style="display: none;height: 100%;">
		    <div style="display: flex;height: 100%;overflow: auto;flex-direction: column;">
				<div id="toolbar-container"><!-- 工具栏 --></div>
				<div id="editor-container" style="flex:1"><!-- 编辑器 --></div>
			</div>
		</div>

	</form>
</div>
{{template "admin/bodyend.html"}}

<script>
	layui.use(function () {
		var form = layui.form;
		var layer = layui.layer;
		var upload = layui.upload;
		var $ = layui.jquery;
   
		//选中导航菜单
		$("#categoryID option[value='{{.Data.CategoryID}}']").attr("selected", true);
		//选中模板
		$("#templateFile option[value='{{.Data.TemplateFile}}']").attr("selected", true);
		//选中状态
		$("#status option[value='{{.Data.Status}}']").attr("selected", true);

		// 缩略图
		var thumbnail = "{{.Data.Thumbnail}}";
        if (thumbnail!=""){
            $("#img_thumbnail").attr("src",basePath+thumbnail);
			$("#i_delete_thumbnail").show();
		}

		var content = "";
		if("{{.Data.Markdown}}"==""){//不是markdown格式
			content="{{.Data.Content}}";
			$("input:radio[name='contentType'][value='1']").attr("checked",true);  
			$('#markdown-container').hide()
			$('#editor-wrapper').show()
		}
		// 渲染全部表单
		form.render(); 

		// 上传文件
		upload.render({
			elem: '#button-upload-thumbnail',
			url: '{{basePath}}admin/upload', // 此处配置你自己的上传接口即可
			size: 20 * 1024, // 限制文件大小,单位 KB
			data: {
				dirPath: function(){
					return $('#categoryID').val()+"{{lastURI .Data.Id}}"; // 目录路径
				}
			},
			before: function(obj){ 
				// 没有选择导航菜单返回false,阻止上传
				if($('#categoryID').val()==""){
					layer.msg('{{T "Navigation menu cannot be empty"}}');
					return false;
				}
			},
			done: function (res) {
				if (res.statusCode == 1) {
					thumbnail =res.data;
					$("#img_thumbnail").attr("src",  basePath+thumbnail);
					$("#i_delete_thumbnail").show();
				}
				console.log(res);
			}
		});

		$("#i_delete_thumbnail").click(function () {
			thumbnail="";
			$("#img_thumbnail").attr("src", "");
			$("#i_delete_thumbnail").hide();
		})

		$("#img_thumbnail").click(function () {
			layer.photos({
				photos: {
					"title": '{{T "Cover Image"}}',
					"start": 0,
					"data": [{
					  "src": basePath+thumbnail,
					}]
				},
				//toolbar: false,
				footer: false // 是否显示底部栏 --- 2.8.16+
			});
		});

		var funcFileUpload=function (file, callback) {
				// 没有选择导航菜单返回false,阻止上传
				if($('#categoryID').val()==""){
					layer.msg('{{T "Navigation menu cannot be empty"}}');
					return false;
				}
				var formdata = new FormData(); // FormData对象,来发送二进制文件.
				formdata.append('file', file); // 将文件追加到 formdata对象中
				formdata.append('dirPath',  $('#categoryID').val()+"{{lastURI .Data.Id}}"); // 目录路径
				$.ajax({
					type: 'post',
					url: '{{basePath}}admin/upload',
					data: formdata,
					processData: false,
					contentType: false,
					success(res) {
						callback(basePath+res.data);
					},
					error(err) { },
				});
			};

		var cherryLocale="zh_CN";
		if (locale!='zh-CN'){
			cherryLocale="en_US";
		}
		// cherry markdown 编辑器
		var cherry = new Cherry({
			locale: cherryLocale,
			id: 'markdown-container',
			value: '{{.Data.Markdown}}',
			autoSave2Textarea: true,
            defaultModel: 'edit&preview',
			fileUpload: funcFileUpload,
			toolbars: {
				// 定义顶部工具栏
				toolbar: [
				'bold',
				'italic',
				{
					strikethrough: ['strikethrough', 'underline', 'sub', 'sup', 'ruby', 'customMenuAName'],
				},
				'size',
				'|',
				'color',
				'header',
				'|',
				'ol',
				'ul',
				'checklist',
				'panel',
				'justify',
				'detail',
				'|',
				{
					insert: ['image', 'audio', 'video', 'link', 'hr', 'br', 'code', 'formula', 'toc', 'table', 'pdf', 'word', 'ruby'],
				},
                'graph','togglePreview', 'export'
				],
				// 定义侧边栏,默认为空
				// sidebar: ['theme', 'mobilePreview', 'copy'],
				// 定义顶部右侧工具栏,默认为空
				toolbarRight: ['fullScreen'],
				//显示目录
				toc: {
				  updateLocationHash: false, // 要不要更新URL的hash
				  defaultModel: 'pure', // pure: 精简模式/缩略模式，只有一排小点； full: 完整模式，会展示所有标题
				},
				
				// 定义选中文字时弹出的“悬浮工具栏”,默认为 ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'quote', '|', 'size', 'color']
				bubble: ['bold', 'italic', 'underline', 'strikethrough', 'sub', 'sup', 'ruby', '|', 'color', 'size'],
				// 定义光标出现在行首位置时出现的"提示工具栏",默认为 ['h1', 'h2', 'h3', '|', 'checklist', 'quote', 'table', 'code']
				float: [],
				autoScrollByHashAfterInit: true,
			},
		});

		// 富文本编辑器
		const { createEditor, createToolbar,i18nChangeLanguage } = window.wangEditor
		if (locale!='zh-CN'){ //如果不是中文,就使用英文
			// 切换语言 - 'en' 或者 'zh-CN'
			i18nChangeLanguage('en')
		}
		
		const editorConfig = {
			placeholder: '{{T "Please enter content..."}}',
			MENU_CONF: {},
			onChange(editor) {
				content = editor.getHtml()
				// 也可以同步到 <textarea>
			},
		}
		var editorUploadConfig = {
			 async customUpload(file, insertFn) {       
				funcFileUpload(file,insertFn);
			},
		};
		editorConfig.MENU_CONF['uploadImage'] = editorUploadConfig;
		editorConfig.MENU_CONF['uploadVideo'] = editorUploadConfig;
		const editor = createEditor({
			selector: '#editor-container',
			html: content,
			config: editorConfig,
			mode: 'default', // or 'simple'
		})
		const toolbar = createToolbar({
			editor,
			selector: '#toolbar-container',
			//config: {},
			config: { excludeKeys: ['todo','divider','redo'] },
			mode: 'default', // or 'simple'
		})

		// 切换 富文本 和 Markdown
		form.on('radio(contentType)', function (data) {
			var elem = data.elem; // 获得 radio 原始 DOM 对象
			// var checked = elem.checked; // 获得 radio 选中状态
			var current = elem.value; // 获得 radio 值
			if (current == 0) {
				$('#markdown-container').show()
				$('#editor-wrapper').hide()
			} else {
				$('#markdown-container').hide()
				$('#editor-wrapper').show()
			}
		})


		// 提交事件
		form.on('submit(gpress-form-ajax-update)', function (data) {
			var field = data.field; // 获取表单字段值
			field.sortNo = field.sortNo - 0;
			field.status = field.status - 0;
			field.thumbnail = thumbnail;
			field.code = "";
			field.categoryName = $("#categoryID").find("option:selected").text();
			//选中的文章类型
			let contentType=$("input:radio[name='contentType']:checked").val(); 
			if(contentType=="1"){//富文本
				field.content = content;
				field.markdown= "";
			}else{
				field.content="";
				field.markdown = cherry.getMarkdown();
			}

			//表单对象
			const form = document.getElementById('gpress-form');
			$.ajax({
				url: form.action,
				type: form.method,
				contentType: "application/json;charset=utf-8",
				dataType: "json",
				data: JSON.stringify(field),
				error: function (result) {
					layer.msg('{{T "Update error!"}}'+result.responseJSON.message);
				},
				success: function (result) {
					if (result.statusCode == 1) {
						layer.confirm('{{T "Update successful, continue editing?"}}', {
							icon: 3,
							title: '{{T "Confirm"}}',
							btn: ['{{T "Return to List"}}', '{{T "Continue Editing"}}'] //按钮
						}, function () {
							window.location.href = '{{basePath}}admin/{{.UrlPathParam}}/list?pageNo=1&id='+field.categoryID;
						});
					} else {
						layer.msg('{{T "Update failed!"}}');
					}
				}
			});
			return false; // 阻止默认 form 跳转
		});
	});
</script>